package com.css.zfzx.sjcj.modules.hddcRock5Pre.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.repository.entity.HddcB1GeomorlnonfractbltEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.viewobjects.HddcB1GeomorlnonfractbltVO;
import com.css.zfzx.sjcj.modules.hddcRock5Pre.repository.HddcRock5preNativeRepository;
import com.css.zfzx.sjcj.modules.hddcRock5Pre.repository.HddcRock5preRepository;
import com.css.zfzx.sjcj.modules.hddcRock5Pre.repository.entity.HddcRock5preEntity;
import com.css.zfzx.sjcj.modules.hddcRock5Pre.service.HddcRock5preService;
import com.css.zfzx.sjcj.modules.hddcRock5Pre.viewobjects.HddcRock5preQueryParams;
import com.css.zfzx.sjcj.modules.hddcRock5Pre.viewobjects.HddcRock5preVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author lhl
 * @date 2020-11-27
 */
@Service
public class HddcRock5preServiceImpl implements HddcRock5preService {

	@Autowired
    private HddcRock5preRepository hddcRock5preRepository;
    @Autowired
    private HddcRock5preNativeRepository hddcRock5preNativeRepository;

    @Override
    public JSONObject queryHddcRock5pres(HddcRock5preQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcRock5preEntity> hddcRock5prePage = this.hddcRock5preNativeRepository.queryHddcRock5pres(queryParams, curPage, pageSize, sort, order);
        List<HddcRock5preVO> hddcRock5preVOList = new ArrayList<>();
        List<HddcRock5preEntity> hddcRock5preEntityList = hddcRock5prePage.getContent();
        for(HddcRock5preEntity hddcRock5preEntity : hddcRock5preEntityList){
            HddcRock5preVO hddcRock5preVO = new HddcRock5preVO();
            BeanUtils.copyProperties(hddcRock5preEntity, hddcRock5preVO);
            if(PlatformObjectUtils.isNotEmpty(hddcRock5preEntity.getSymbol())) {
                String dictItemCode=String.valueOf(hddcRock5preEntity.getSymbol());
                hddcRock5preVO.setSymbolName(findByDictCodeAndDictItemCode("RockTypeCVD", dictItemCode));
            }
            hddcRock5preVOList.add(hddcRock5preVO);
        }
        Page<HddcRock5preVO> HddcRock5preVOPage = new PageImpl(hddcRock5preVOList, hddcRock5prePage.getPageable(), hddcRock5prePage.getTotalElements());
        JSONObject jsonObject = PlatformPageUtils.formatPageData(HddcRock5preVOPage);
        return jsonObject;
    }


    @Override
    public HddcRock5preEntity getHddcRock5pre(String id) {
        HddcRock5preEntity hddcRock5pre = this.hddcRock5preRepository.findById(id).orElse(null);
         return hddcRock5pre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRock5preEntity saveHddcRock5pre(HddcRock5preEntity hddcRock5pre) {
        String uuid = UUIDGenerator.getUUID();
        hddcRock5pre.setUuid(uuid);
        hddcRock5pre.setCreateUser(PlatformSessionUtils.getUserId());
        hddcRock5pre.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcRock5pre.setIsValid("1");
        this.hddcRock5preRepository.save(hddcRock5pre);
        return hddcRock5pre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRock5preEntity updateHddcRock5pre(HddcRock5preEntity hddcRock5pre) {
        UpdateUtil.copyNullProperties(hddcRock5preRepository.findByUuidAndIsValid(hddcRock5pre.getUuid(), "1"), hddcRock5pre);
        hddcRock5pre.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcRock5pre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcRock5preRepository.save(hddcRock5pre);
        return hddcRock5pre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcRock5pres(List<String> ids) {
        List<HddcRock5preEntity> hddcRock5preList = this.hddcRock5preRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcRock5preList) && hddcRock5preList.size() > 0) {
            for(HddcRock5preEntity hddcRock5pre : hddcRock5preList) {
                hddcRock5pre.setIsValid("0");
                hddcRock5pre.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRock5pre.setUpdateTime(new Date());
                this.hddcRock5preRepository.save(hddcRock5pre);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String findByDictCodeAndDictItemCode(String dictCode, String dictItemCode){
        DictItemEntity dictItem = PlatformAPI.getDictAPI().getValidDictItemByDictCodeAndDictItemCode(dictCode, dictItemCode);
        String dictItemName = "";
        if(PlatformObjectUtils.isNotEmpty(dictItem)){
            dictItemName = dictItem.getDictItemName();
        }
        return dictItemName;
    }

    @Override
    public void exportFile(HddcRock5preQueryParams queryParams, HttpServletResponse response) {
        List<HddcRock5preEntity> yhDisasterEntities = hddcRock5preNativeRepository.exportYhDisasters(queryParams);
        List<HddcRock5preVO> list=new ArrayList<>();
        for (HddcRock5preEntity entity:yhDisasterEntities) {
            HddcRock5preVO yhDisasterVO=new HddcRock5preVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"1：5万工作底图岩体-面","1：5万工作底图岩体-面",HddcRock5preVO.class,"1：5万工作底图岩体-面.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcRock5preVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcRock5preVO.class, params);
            List<HddcRock5preVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcRock5preVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcRock5preVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcRock5preVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcRock5preEntity yhDisasterEntity = new HddcRock5preEntity();
            HddcRock5preVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcRock5pre(yhDisasterEntity);
        }
    }
}
